% use DistP2Segment
clc; clear; 

P = [15;5];

Seg = [0 2; 1 2 ];


% a = (Seg(2,2)-Seg(2,1))/(Seg(1,2)-Seg(1,1));   
% b = (Seg(1,2)*Seg(2,1)-Seg(1,1)*Seg(2,2))/(Seg(1,2)-Seg(1,1));
% 
% dBC = [Seg(1,2)-Seg(1,1);Seg(2,2)-Seg(2,1)];
% 
% a2 = dBC(1);
% b2 = dBC(2);
% c2 = P(1)*a2+P(2)*b2;
% 
% A = [a2 b2; a -1];
% B = [c2; -b];      % B here not point B but is B matrix in Cramer's rule
% A1 = [B A(:,2)];
% A2 = [A(:,1) B];
% 
% H = [det(A1)/det(A); det(A2)/det(A)];
% 
% minx = min(Seg(1,:));
% miny = min(Seg(2,:));
% maxx = max(Seg(1,:));
% maxy = max(Seg(2,:));
% 
% if (minx<=H(1))&&(H(1)<=maxx)&&(miny<=H(2))&&(H(2)<=maxy)
%     y = norm([H(1)-P(1) H(2)-P(2)])
% else 
%     dP2B = norm([Seg(1,1)-P(1) Seg(2,1)-P(2)]);
%     dP2C = norm([Seg(1,2)-P(1) Seg(2,2)-P(2)]);
%     y = min(dP2B, dP2C)
% end

H = DistP2Segment(P,Seg)

plot(Seg(1,:),Seg(2,:))

hold on;

plot(P(1,:),P(2,:),'k*');

% plot(H(1,:),H(2,:),'r*');

axis equal;